<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect
              v-model="form.userId"
              style="height:36px;"
              :placeholder="this.$t('选择用户')"
              @change="changeName"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请部门')" prop="deptId">
            <DeptSelect v-model="form.deptId" :placeholder="$t('申请部门')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人岗位')" prop="postIds">
            <el-select v-model="form.postIds" multiple :placeholder="$t('请选择')" disabled>
              <el-option
                v-for="item in postOptions"
                :key="item.postId"
                :label="$t(item.postName)"
                :value="item.postId"
                disabled
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计金额(元)')" prop="money">
            <money v-model="form.money" :placeholder="$t('预计金额(元)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('出差方式')" prop="method">
            <el-checkbox-group v-model="form.method">
              <el-checkbox-button
                v-for="item in methodsOptions"
                :key="item.dictValue"
                :label="item.dictValue"
              > {{ $t(item.dictLabel) }}
              </el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('出差类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('请选择')" filterable>
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('目的地类型')" prop="destination">
            <dictSelect
              v-model="form.destination"
              :clearable="true"
              dictionary="destination_type"
              :placeholder="$t('目的地类型')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否确定往返时间')" prop="isDetermine">
            <dictSelect
              v-model="form.isDetermine"
              :clearable="true"
              dictionary="sys_yes_no"
              :placeholder="$t('是否确定往返时间')"
              @change="changeR"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('时间')" prop="goOffArry">
            <el-date-picker
              v-model="form.goOffArry"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="/"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')"
              format="yyyy-MM-dd HH:mm"
              :default-time="['09:00:00', '18:00:00']"
              @change="goOffArryChange"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('出差天数')" prop="days">-->
        <!--            <el-input-number-->
        <!--              v-model="form.days"-->
        <!--              :placeholder="$t('出差天数')"-->
        <!--              :max="9999"-->
        <!--              :controls="false"-->
        <!--              :precision="0"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12">
          <el-form-item :label="$t('内部同行人员')" prop="internalColleagues">
            <UserSelect
              v-model="form.internalColleagues"
              :multiple="true"
              :placeholder="this.$t('选择用户')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('其他同行人员')" prop="partnersId">
            <el-input v-model="form.partnersId" :placeholder="$t('其他同行人员')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('出差事由') }}</span>
      </div>
      <el-table :data="form.reasonsList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('起始时间')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('时间') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'reasonsList.' + scope.$index + '.timeArray'" :rules="rules.timeArray">
              <el-date-picker
                v-model="scope.row.timeArray"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="-"
                :start-placeholder="$t('开始日期')"
                :end-placeholder="$t('结束日期')"
                align="right"
                format="yyyy-MM-dd HH:mm"
                :default-time="['09:00:00', '18:00:00']"
                size="small"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('事由')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('事由') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'reasonsList.' + scope.$index + '.reason'" :rules="rules.reason">
              <el-input
                v-model="scope.row.reason"
                :placeholder="$t('事由')"
                type="textarea"
                maxlength="2000"
                :autosize="{ minRows: 1, maxRows: 10}"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-if="!otherBtnHide" v-hasPermi="['oa:travel:remove']" size="small" type="text" icon="el-icon-delete" @click="delRow(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button v-if="!otherBtnHide" v-hasPermi="['oa:travel:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addRow">{{ $t('添加') }}</el-button>
      </div>

      <!--文件-->
      <FileTable :list.sync="form.fileList" :data-type="dataType" :btn-show="!otherBtnHide" />

    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:travel" :menu-key="menuKey" />
    </div>

    <!-- 预览附件 -->
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import { saveOaBusinessTravel, getOaBusinessTravel, deleteReasons } from '@/api/oa/travel/oaTravel'
import { parseTime } from '@/utils/ruoyi'
import { listPost } from '@/api/system/post'
import { getUser } from '@/api/system/user'

export default {
  name: 'OaTravelForm',
  components: {
  },
  // props: ['oaBusinessTravelData'],
  data() {
    // const checkRules = (rule, value, callback) => {
    //   if (value === 0 || value === '0') {
    //     callback(new Error('预计金额不能为0元'))
    //   }
    //   if (value === undefined || value === '' || value === null) {
    //     callback(new Error('不能为空'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      // 菜单标识
      menuKey: 'oa_travel',
      otherBtnHide: false,
      loading: false,
      openLocation: undefined,
      title: '',
      oaBusinessTravelData: undefined,
      uploaderOpen: false,
      dataType: 'oa_travel',
      // 表单参数
      form: {
        method: [],
        // 出差事由
        reasonsList: [],
        uploadFile: [],
        fileList: []
      },
      // 表单校验
      rules: {
        // money: { required: true, validator: checkRules, trigger: 'blur' },
        userId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        type: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        method: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        placeDeparture: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        destination: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        goOffArry: [],
        deptId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        // postIds: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        applyTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        days: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        isDetermine: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        actTitle: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      // 出差类型
      typeOptions: [],
      // 出差方式
      methodsOptions: [],
      // 岗位选项
      postOptions: [],
      pickerOptions: {
        shortcuts: [{
          text: this.$t('最近一周'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('最近一个月'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('最近三个月'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    oaBusinessTravelData: function() {
      this.form = this.oaBusinessTravelData
    }
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  created() {
    this.initDict()
  },
  methods: {
    // 添加附件
    uploader() {
      this.uploaderOpen = true
      this.title = '上传附件'
    },
    // 获取附件列表
    getData(fileList) {
      this.form.fileList = fileList
    },
    // 删除附件
    delAdjunct(index) {
      this.form.fileList.splice(index, 1)
    },
    // 预览附件
    onlinePreview(row) {
      this.$refs.OnlinePreview.onlinePreviewFile(row.id)
    },
    // 初始化数据
    init(data) {
      if (data != null && data !== '' && data.id !== undefined) {
        this.loading = true
        getOaBusinessTravel(data.id).then(response => {
          this.form = response.data
          console.log(response.data)
          console.log(this.form.postIds)
          this.loading = false
        })
      } else {
        this.reset()
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: this.$store.state.user.userId,
        partnersId: undefined,
        internalColleagues: undefined,
        type: undefined,
        method: [],
        placeDeparture: undefined,
        destination: undefined,
        goOff: undefined,
        endTimes: undefined,
        days: undefined,
        money: undefined,
        remark: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actTitle: undefined,
        applyTime: undefined,
        postIds: [],
        deptId: undefined,
        isDetermine: undefined,
        reasonsList: []
      }
      this.initReset()
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      if (this.$parent.$parent.reset !== undefined) {
        this.$parent.$parent.reset()
      }
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            saveOaBusinessTravel(this.form).then(response => {
              if (response.code === 200) {
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.form.id = response.data.id
                  this.startProcess(response.data)
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.locationError(document)
            reject()
          }
        })
      })
    },
    // 启动流程
    startProcess: function(data) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // + '(' + data.placeDeparture + ' - ' + data.destination + ')'
      // 业务表名
      processData.dataTable = 'oa_travel'
      // 业务ID
      processData.dataId = data.id
      // 业务表单地址
      processData.formPath = '@/views/oa/travel/oaTravelForm'

      // 业务表单打印地址
      processData.viewPath = '@/views/oa/travel/oaTravelView'

      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 添加出差事由
    addRow() {
      const row = {
        id: '',
        timeArray: [],
        reason: ''
      }
      this.form.reasonsList.push(row)
    },
    // 删除出差事由
    delRow(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
              return deleteReasons(id)
            }).then(() => {
          this.form.reasonsList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
            })
      } else {
        this.form.reasonsList.splice(index, 1)
      }
    },
    // 选择时间后计算出差天数
    goOffArryChange(val) {
      var start = new Date(parseTime(val[0]))
      var end = new Date(parseTime(val[1]))
      this.form.days = (end.getTime() - start.getTime()) / 1000 / 60 / 60 / 24
    },
    initDict() {
      // 出差类型
      this.getDicts('oa_business_travel_type').then(response => {
        this.typeOptions = response.data
      })
      // 出差方式
      this.getDicts('oa_business_travel_methods').then(response => {
        this.methodsOptions = response.data
      })
      listPost({}).then(res => {
        this.postOptions = res.rows
      })
    },
    changeName() {
      console.log('ss')
      getUser(this.form.userId).then(response => {
        this.$set(this.form, 'postIds', response.datas.postIds)
        this.$set(this.form, 'deptId', response.data.deptId)
      })
    },
    // 初始化重置表单 数据
    initReset() {
      // 获取当前时间
      const now = new Date()
      const year = now.getFullYear() // 得到年份
      let month = now.getMonth() // 得到月份
      let date = now.getDate() // 得到日期
      month = month + 1
      month = month.toString().padStart(2, '0')
      date = date.toString().padStart(2, '0')
      this.form.applyTime = `${year}-${month}-${date}`
      this.changeName()
    },
    changeR() {
      console.log()
      if (this.form.isDetermine === 'Y') {
        this.rules.goOffArry = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      } else {
        this.rules.goOffArry = [{ required: false, trigger: 'blur' }]
        this.$refs['form'].validate()
        // this.$refs['form'].resetFields()
      }
    }

  }

}
</script>
<style scoped>
.addFile {
  width: 73px;
  height: 29px;
  line-height: 15px;
  padding: 7px 15px;
  font-size: 12px;
  border-radius: 3px;
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
  cursor: pointer;
}

.el-textarea el-input--medium {
  margin: 0px 0px;
}
</style>
